/**
 * Created by Lee on 2017/7/28.
 */

$(function () {

	//有选择的Id数据
	var selectedGoodsIdArr = [];

	var defUrl = "http://yunyingadmin.dtk.quan007.com/index.php?r=api/goods-filter"; //默认加载地址
	var reqUrl; //请求地址

	var addMaxNum = 200; //最大可以选择多少个商品
	var selectedNum = 0; //已选择的数量
	var allPage;

	//初始化加载数据
	ajaxReq(defUrl);

	//渲染模板
	function setTpl(params, ele, path) {
		var _html = [];
		for(var i = 0; i < params.length; i++) {
			_html += '<li data-id="'+params[i]._source.id+'">'
				+'<div class="list-pic">'
				+'<img src="'+params[i]._source.pic+'_230x230.jpg" alt="">'
				+'</div>'
				+'<div class="list-main">'
				+'<div class="title">'+params[i]._source.d_title+'</div>'
				+'<div class="coupon">券后<span>'+params[i]._source.jiage+'</span> 券<span>'+params[i]._source.quan_jine+'</span> '+resetType(params[i]._source.yongjin_type, params[i]._source.jihua_link)+' <span>'+params[i]._source.yongjin+'</span>%</div>'
				+'<div class="cate">'+getCate(params[i]._source.cid)+'</div>'
				+'<div class="time">'+params[i]._source.quan_time+'</div>'
				+'</div>'
				+'<div class="list-op">'
				+'<a href="http://www.dataoke.com/item?id='+params[i]._source.id+'" target="_blank">详情</a>'
				+'<a href="javascript:;" class="full-query-list-select">选择</a>'
				+'</div>'
				+'</li>'
		}
		if(path == "h") {
			$(ele).html("");
			$(ele).html(_html);
		} else {
			$(ele).append(_html);
		}
	}

	//选择和取消选择
	$("body").on("click", "#fullQueryList .full-query-list-select", function (event) {
		var event = event || window.event;
		event.preventDefault();
		var me = $(this);
		var par = $(this).parents("li");
		if(par.hasClass("active")) {
			par.removeClass("active");
			removeSelectedGoodsList(par.data("id"));
			me.text("选择");
		} else {
			if(addMaxNum == selectedNum) {
				layer.msg("最多只能添加"+addMaxNum+"个商品");
				return;
			} else {
				par.addClass("active");
				addSelectedGoodsList(par.data("id"), par.find("img").attr("src"));
				me.text("取消选择");
			}
		}
	});

	//在已选列表中移除
	$("body").on("click", "#selectedListGoodsArea li button", function () {
		var me = $(this);
		me.parents("li").remove();
		$("#fullQueryList li").each(function () {
			if(me.parents("li").data("id") == $(this).data("id")) {
				$(this).removeClass("active");
			}
		});
		getSelectedNums();
	});

	//筛选
	$("body").on("click", "#fullQuerySelectionBtn", function () {
		var url = defUrl + "&" + $("#full-query-search-from").serialize();
		ajaxReq(url);
	});

	//清除筛选
	$("body").on("click", "#fullQuerySelectionNullBtn", function () {
		$("#full-query-search-from input").attr("checked", false);
		ajaxReq(defUrl);
	});

	//翻页
	$("body").on("click", "#fullQueryPagesBox li", function () {
		if($(this).hasClass("active")) {
			return false;
		}
		var p = $(this).data("page");
		ajaxReq(resetUrlPages(p), p);
	});

	//确认使用
	$("#cfm-use-btn").on("click", function () {
		getSelectedIdArr();
		outputSelectedIdArr();
		parent.layer.closeAll();
	});

	//显示和隐藏已选
	$(".selected-dis-hide").on("click", function () {
		var me = $(this);
		var ele = me.parents(".goods-selected-dis").find(".selected-list-goods");
		if(ele.hasClass("show")) {
			ele.removeClass("show");
			me.text("查看已选");
		} else {
			ele.addClass("show");
			me.text("关闭已选");
		}
	});

	//跳转输入页码
	$("#jump-page-btn").on("click", function () {
		var p = parseInt($.trim($("#jump-page-val").val()));
		if(p.length == 0) {
			layer.msg("页面输入不能为空")
		} else {
			ajaxReq(resetUrlPages(p), p);
		}
	});

	//enter输入跳转页面
	$("#jump-page-val").keyup(function (e) {
		if(e.keyCode == 13) {
			var p = $(this).val();
			if(p > allPage) {
				layer.msg("你输入的页码有误");
				return;
			}
			if(p.length == 0) {
				layer.msg("页面输入不能为空")
			} else {
				ajaxReq(resetUrlPages(p), p);
			}
		}
	});

	//重置url
	function resetUrlPages(p) {
		var pageReg = new RegExp("page");
		if(p != undefined) {
			if(pageReg.test(reqUrl)) {
				return reqUrl.split("page=")[0] + "page=" + p;
			} else {
				return reqUrl + "&page=" + p;
			}
		}
	}

	//重置：定向、通用、高佣、销售
	function resetType(type, link) {
		if(type == 1) {
			if(link.length > 20) {
				return "定向"
			} else {
				return "通用"
			}
		} else if (type == 2) {
			return "高佣"
		} else if (type == 3) {
			return "销售"
		}
	}

	//获取分类
	function getCate(cid) {
		switch (cid) {
			case 1:
				return "女装";
				break;
			case 2:
				return "母婴";
				break;
			case 3:
				return "化妆品";
				break;
			case 4:
				return "居家";
				break;
			case 5:
				return "鞋包配饰";
				break;
			case 6:
				return "美食";
				break;
			case 7:
				return "文体车品";
				break;
			case 8:
				return "数码家电";
				break;
			case 9:
				return "男装";
				break;
			case 10:
				return "内衣";
				break;
			default :
				return "其它"
		}
	}

	//获取已选中的数量
	function getSelectedNums() {
		selectedNum = $("body #selectedListGoodsArea li").length;
		$("#selected-goods-num").text(selectedNum);
	}

	//输出到父集ID数据存在位置
	function outputSelectedIdArr() {
		var parEle = parent.document.getElementById('fullQuerySelectedIdArr');
		var parEleVal = parEle.value.split(",");
		console.log(parEleVal);
		parEle.value = filterSame(parEleVal.concat(selectedGoodsIdArr));
	}

	//添加已选中的列表
	function addSelectedGoodsList(id, pic) {
		var _html = '<li data-id="'+id+'">'
			+'<img src="'+pic+'" alt="">'
			+'<button type="button">移出</button>'
			+'</li>';
		$("#selectedListGoodsArea").append(_html);
		getSelectedNums();
		getSelectedIdArr();
	}

	//移除取消选择的列表
	function removeSelectedGoodsList(id) {
		$("body #selectedListGoodsArea li").each(function () {
			if($(this).data("id") == id) {
				$(this).remove();
				getSelectedNums();
				getSelectedIdArr();
			}
		});
		getSelectedIdArr();
	}

	//获取已选中的ID数组
	function getSelectedIdArr() {
		selectedGoodsIdArr = [];
		$("body #selectedListGoodsArea li").each(function () {
			selectedGoodsIdArr.push($(this).data("id"));
		});
	}

	//ajax加载页面数据
	function ajaxReq(url, p) {
		var dataLoad = layer.load();
		var nP;
		if(p == undefined) {
			nP = 1;
		} else {
			nP = p
		}
		$.ajax({
			url: url,
			type: "get",
			dataType: "json",
			timeout: 20000,
			success: function (res) {
				var obj = {
					listEle: "#fullQueryList",
					p: res.page,
					dataLen: res.data.length,
					noneEle: "#full-query-list-none",
					pageEle: "#full-query-pagination"
				};
				if(res.data.length == 0) {
					commonShowHide(obj);
				} else {
					getSelectedIdArr();
					setTpl(res.data, "#fullQueryList", "h");
					allPage = res.page;
					reqUrl = url;
					commonShowHide(obj);
					outputPagination(allPage, nP, "#fullQueryPagesBox");
					if(selectedGoodsIdArr.length != 0) {
						for(var i  = 0; i < selectedGoodsIdArr.length; i++) {
							removeActiveCls(selectedGoodsIdArr[i]);
						}
					}
				}
				layer.close(dataLoad);
			},
			error: function (err) {
				console.log(err);
				layer.close(dataLoad);
			}
		});
	}

	//翻页
	function outputPagination(allPage, nowPage, dom) {

		var pArr = new Array();
		var pages = new Array();
		var singleReg = new RegExp("single");
		var activeReg = new RegExp("active");
		var moreReg = new RegExp("more");
		var totalPage = allPage - nowPage;

		if(allPage <= 6) {
			pArr = allPage + "single";
		} else if(totalPage > 4) {
			if(nowPage === 1) {
				pArr[0] = 1 + "active";
				pArr[1] = 2;
				pArr[2] = 3;
			} else {
				pArr[0] = nowPage - 1;
				pArr[1] = nowPage + "active";
				pArr[2] = parseInt(nowPage) + 1;
			}
			pArr[3] = "more";
			pArr[4] = allPage - 2;
			pArr[5] = allPage - 1;
			pArr[6] = allPage;
		} else {
			pArr[0] = 1;
			pArr[1] = "more";
			var pNUm = 4;
			for(var i = 2; i < 7; i++) {
				if(allPage - pNUm == nowPage) {
					pArr[i] = allPage - pNUm + "active";
				} else {
					pArr[i] = allPage - pNUm;
				}
				pNUm--;
			}
		}

		if(singleReg.test(pArr)) {
			for(var i = 0; i < parseInt(pArr); i++) {
				var val = i + 1;
				if(val == nowPage) {
					pages.push("<li class='active' data-page='"+val+"'>"+val+"</li>");
				} else {
					pages.push("<li data-page='"+val+"'>"+val+"</li>");
				}
			}
		} else {
			for(var i = 0; i < pArr.length; i++) {
				if(activeReg.test(pArr[i])) {
					pages.push("<li class='active' data-page='"+pArr[i]+"'>"+parseInt(pArr[i])+"</li>");
				} else if(moreReg.test(pArr[i])) {
					pages.push("<li class='more'>...</li>");
				} else {
					pages.push("<li data-page='"+pArr[i]+"'>"+pArr[i]+"</li>");
				}
			}
		}

		$(dom).html(pages);
	}

	//分页、无数据及数组显示隐藏切换
	function commonShowHide(obj) {
		if(obj.p > 1) {
			$(obj.pageEle).show();
		} else {
			$(obj.pageEle).hide();
		}
		if(obj.dataLen == 0) {
			$(obj.noneEle).show();
			$(obj.listEle).hide();
		} else {
			$(obj.listEle).show();
			$(obj.noneEle).hide();
		}
	}

	//跨页移出已取消的选择项
	function removeActiveCls(id) {
		$("body #fullQueryList li").each(function () {
			var listId = $(this).data("id");
			if(listId == id) {
				$(this).addClass("active");
			}
		});
	}

	//过滤相同数组字段
	function filterSame(arr) {
		console.log(arr);
		var result = [],
			hash = {};
		for(var i = 0, elem;
		    (elem = arr[i]) != null; i++) {
			if(!hash[elem]) {
				if(elem != "") {
					result.push(elem);
					hash[elem] = true;
				}
			}
		}
		return result.join("#");
	}
});